//
//  loginController.m
//  pacc
//
//  Created by 测试 on 2018/5/21.
//  Copyright © 2018年 测试. All rights reserved.
//

#import "loginController.h"
#import "ZXTabBarController.h"
#import "changepasswordController.h"
@interface loginController ()<RHURLRequestDelegate,UITextFieldDelegate>
- (IBAction)changPasswordClick:(id)sender;
@property(strong,nonatomic)NetWorking *request;
@property (weak, nonatomic) IBOutlet UITextField *zhanghaoTF;
@property (weak, nonatomic) IBOutlet UITextField *mimaTf;
@property (weak, nonatomic) IBOutlet UIView *zhanghaoView;
@property (weak, nonatomic) IBOutlet UIView *mimaView;
@property (weak, nonatomic) IBOutlet UIView *loginView;
@property (weak, nonatomic) IBOutlet UIView *phoneLoginView;
@property (weak, nonatomic) IBOutlet UIButton *zhanghaomimaBtn;
@property (weak, nonatomic) IBOutlet UIButton *yanzhengmaBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTF;
@property (weak, nonatomic) IBOutlet UITextField *yanzhengmaTF;
@property (weak, nonatomic) IBOutlet UIView *phoneNumberView;
@property (weak, nonatomic) IBOutlet UIView *yanzhengmaView;
@property (weak, nonatomic) IBOutlet UIButton *huoquyanzhengmaBtn;
- (IBAction)huoquyanzhengmaClick:(id)sender;
@property(assign ,nonatomic)BOOL isYanzhengmaLogin;
@end

@implementation loginController

- (void)viewDidLoad {
    [super viewDidLoad];
    [_zhanghaomimaBtn setTitleColor:RGB(34, 34, 34) forState:UIControlStateNormal];
    [_yanzhengmaBtn setTitleColor:RGB(136, 136, 136) forState:UIControlStateNormal];

}
- (IBAction)backClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)accountLogin:(UIButton *)sender {
    _isYanzhengmaLogin = NO;
    [_zhanghaomimaBtn setTitleColor:RGB(34, 34, 34) forState:UIControlStateNormal];
    [_yanzhengmaBtn setTitleColor:RGB(136, 136, 136) forState:UIControlStateNormal];

    [UIView animateWithDuration:0.5 animations:^{
        self->_loginView.x = 0;
        self->_phoneLoginView.x = self.view.width;

    } completion:^(BOOL finished) {
        [self->_zhanghaoTF becomeFirstResponder];
        
    }];
}
- (IBAction)phoneNumber:(UIButton *)sender {
    [_yanzhengmaBtn setTitleColor:RGB(34, 34, 34) forState:UIControlStateNormal];
    [_zhanghaomimaBtn setTitleColor:RGB(136, 136, 136) forState:UIControlStateNormal];
    _isYanzhengmaLogin = YES;
    [UIView animateWithDuration:0.5 animations:^{
        self->_loginView.x = -self.view.width;
        self->_phoneLoginView.x = 0;

    } completion:^(BOOL finished) {
        [self->_phoneNumberTF becomeFirstResponder];
        
    }];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [SVProgressHUD dismiss];
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
#pragma mark --textfiled delegate--
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == _zhanghaoTF) {
        [UIView animateWithDuration:0.3 animations:^{
            self->_zhanghaoView.width = self->_zhanghaoTF.width;
        } completion:^(BOOL finished) {
            
        }];
    }else if (textField == _mimaTf){
        [UIView animateWithDuration:0.3 animations:^{
            self->_mimaView.width = self->_zhanghaoTF.width;
            
        } completion:^(BOOL finished) {
            
        }];
    }else if (textField == _phoneNumberTF){
        [UIView animateWithDuration:0.3 animations:^{
            self->_phoneNumberView.width = self->_zhanghaoTF.width;
            
        } completion:^(BOOL finished) {
            
        }];
    }else if (textField == _yanzhengmaTF){
        [UIView animateWithDuration:0.3 animations:^{
            self->_yanzhengmaView.width = self->_zhanghaoTF.width;
            
        } completion:^(BOOL finished) {
            
        }];
    }
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField == _zhanghaoTF) {
        [UIView animateWithDuration:0.3 animations:^{
            self->_zhanghaoView.width = 0;
        } completion:^(BOOL finished) {
            
        }];
    }else if (textField == _mimaTf){
        [UIView animateWithDuration:0.3 animations:^{
            self->_mimaView.width = 0;
        } completion:^(BOOL finished) {
            
        }];
    }else if (textField == _phoneNumberTF){
        [UIView animateWithDuration:0.3 animations:^{
            self->_phoneNumberView.width = 0;
            
        } completion:^(BOOL finished) {
            
        }];
    }else if (textField == _yanzhengmaTF){
        [UIView animateWithDuration:0.3 animations:^{
            self->_yanzhengmaView.width = 0;
            
        } completion:^(BOOL finished) {
            
        }];
    }

}
#pragma mark --login--
//登录
- (IBAction)mimingwenBtbClick:(UIButton *)sender {
    _mimaTf.secureTextEntry = !_mimaTf.secureTextEntry;
    if (_mimaTf.secureTextEntry) {
        [sender setImage:[UIImage imageNamed:@"eye_off"] forState:UIControlStateNormal];
    }else [sender setImage:[UIImage imageNamed:@"eye_on"] forState:UIControlStateNormal];
}

- (IBAction)appLoginClick:(UIButton *)sender {
        NSString * zhanghaoStr = _zhanghaoTF.text;
        NSString * mimaStr = _mimaTf.text;
        NSString * PhoneStr = _phoneNumberTF.text;
        NSString * YanzhengmaStr = _yanzhengmaTF.text;
    
    #if defined (__i386__) || defined (__x86_64__)
    
//            zhanghaoStr = @"15026528072";
        zhanghaoStr = @"15921617812";
//            zhanghaoStr = @"15267850997";
//            zhanghaoStr = @"admin";
//            zhanghaoStr =@"15801194833";
//            zhanghaoStr =@"13816687727";
            mimaStr = @"123456";
    
    #else
//    zhanghaoStr = @"15267850997";
//    mimaStr = @"1";

//    zhanghaoStr = @"admin";
////    zhanghaoStr = @"15026528072";
//        zhanghaoStr = @"15026528072";
//
//        mimaStr = @"123456";
    #endif
    
        if (_isYanzhengmaLogin) {
            if (PhoneStr.length&&YanzhengmaStr.length) {
                NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                [dic setValue:PhoneStr forKey:@"uname"];
                [dic setValue:YanzhengmaStr forKey:@"password"];
                [dic setValue:my_AppDelegate.registrationId forKey:@"registrationId"];
                [NetWorking startPOSTRequestWithUrl:@"userphoneLogin" parameters:@{@"phone":PhoneStr, @"phoneCode":YanzhengmaStr}logMes:@"验证码登录" show:YES success:^(NSDictionary *data) {
                    NSDictionary * dic = data;
                    if (!data) {
                        return;
                    }
                    NSString *status = [NSString stringWithFormat:@"%@",[dic objectForKey:@"status"]];
                    if ([status isEqualToString:@"200"]) {
                        NSString *token = [dic objectForKey:@"data"];
                        [[NSUserDefaults standardUserDefaults]setValue:token forKey:@"token"];
                        [[NSUserDefaults standardUserDefaults]synchronize];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            my_AppDelegate.token = token;
                            NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
                            [parameters setValue:my_AppDelegate.token forKey:@"token"];
                            [NetWorking startPOSTRequestWithUrl:[NSString stringWithFormat:@"usergetPermissions"] parameters:parameters logMes:@"获取权限" show:NO success:^(NSDictionary *data) {
                                NSString * status = [NSString stringWithFormat:@"%@",[data objectForKey:@"status"]];
                                if ([status isEqualToString:@"200"]) {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        NSArray * roleArr = [data objectForKey:@"data"];
                                        my_AppDelegate.placeO = NO;
                                        my_AppDelegate.urgeO = NO;
                                        my_AppDelegate.transferO = NO;
                                        my_AppDelegate.grabO = NO;
                                        my_AppDelegate.writeR = NO;
                                        my_AppDelegate.auditR = NO;
                                        my_AppDelegate.login = NO;
                                        my_AppDelegate.assignO = YES;

                                        for (NSString * str in roleArr) {
                                            NSLog(@"权限 = %@ ",str);
                                            if ([str isEqualToString:@"placeO"]) {
                                                if (roleArr.count == 3) {
                                                    my_AppDelegate.placeO = YES;
                                                    [SVProgressHUD showErrorWithStatus:@"暂无权限,无法登陆"];
                                                    return ;
                                                }
                                            }if ([str isEqualToString:@"urgeO"]) {
                                                my_AppDelegate.urgeO = YES;
                                                
                                            }if ([str isEqualToString:@"transferO"]) {
                                                my_AppDelegate.transferO = YES;
                                                
                                            }if ([str isEqualToString:@"grabO"]) {
                                                my_AppDelegate.grabO = YES;
                                                
                                            }if ([str isEqualToString:@"writeR"]) {
                                                my_AppDelegate.writeR = YES;
                                                
                                            }if ([str isEqualToString:@"auditR"]) {
                                                my_AppDelegate.auditR = YES;
                                                
                                            }if ([str isEqualToString:@"assignO"]) {
                                                my_AppDelegate.assignO = YES;
                                                
                                            }if ([str isEqualToString:@"login"]) {
                                                my_AppDelegate.login = YES;
                                                
                                            }
                                        }
                                        [self quitLoginViewController];
                                    });
                                }else{
                                    NSString *msg = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
                                    [SVProgressHUD showErrorWithStatus:msg];
                                     }
                            } failure:^(NSError *error) {
                                [SVProgressHUD showErrorWithStatus:@"登录失败"];
                            }];
                        });
                    }else{
                        NSString *msg = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msg"]];
                        [SVProgressHUD showErrorWithStatus:msg];
                        [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SVProgressHUD dismiss];
                        });
                    }
                } failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"登录失败"];
                }];
            }else {
                [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号和验证码"];
                [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
            }
        }else{
            if (zhanghaoStr.length&&mimaStr.length) {
                NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                [dic setValue:zhanghaoStr forKey:@"uname"];
                [dic setValue:mimaStr forKey:@"password"];
                [dic setValue:my_AppDelegate.registrationId forKey:@"registrationId"];
                [NetWorking startPOSTRequestWithUrl:@"applogin" parameters:dic logMes:@"密码登录" show:YES  success:^(NSDictionary *data) {
                    NSDictionary * dic = data;
                    NSString *status = [NSString stringWithFormat:@"%@",[dic objectForKey:@"status"]];
                    if ([status isEqualToString:@"200"]) {
                        NSString *token = [dic objectForKey:@"data"];
                        [[NSUserDefaults standardUserDefaults]setValue:token forKey:@"token"];
                        [[NSUserDefaults standardUserDefaults]synchronize];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            my_AppDelegate.token = token;
                            [NetWorking startPOSTRequestWithUrl:[NSString stringWithFormat:@"usergetPermissions"] parameters:@{@"token":my_AppDelegate.token} logMes:@"密码登录获取权限" show:NO success:^(NSDictionary *data) {
                                NSString * status = [NSString stringWithFormat:@"%@",[data objectForKey:@"status"]];
                                if ([status isEqualToString:@"200"]) {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        NSArray * roleArr = [data objectForKey:@"data"];
                                        
                                        my_AppDelegate.placeO = NO;
                                        my_AppDelegate.urgeO = NO;
                                        my_AppDelegate.transferO = NO;
                                        my_AppDelegate.grabO = NO;
                                        my_AppDelegate.writeR = NO;
                                        my_AppDelegate.auditR = NO;
                                        my_AppDelegate.login = NO;
                                        my_AppDelegate.assignO = YES;

                                        for (NSString * str in roleArr) {
                                            NSLog(@"权限 = %@ ",str);
                                            if ([str isEqualToString:@"placeO"]) {
                                                my_AppDelegate.placeO = YES;
                                                if (roleArr.count == 3) {
                                                    [SVProgressHUD showErrorWithStatus:@"暂无权限,无法登陆"];
                                                    return ;
                                                }
                                            }if ([str isEqualToString:@"urgeO"]) {
                                                my_AppDelegate.urgeO = YES;

                                            }if ([str isEqualToString:@"transferO"]) {
                                                my_AppDelegate.transferO = YES;

                                            }if ([str isEqualToString:@"grabO"]) {
                                                my_AppDelegate.grabO = YES;

                                            }if ([str isEqualToString:@"writeR"]) {
                                                my_AppDelegate.writeR = YES;

                                            }if ([str isEqualToString:@"auditR"]) {
                                                my_AppDelegate.auditR = YES;

                                            }if ([str isEqualToString:@"assignO"]) {
                                                my_AppDelegate.assignO = YES;

                                            }if ([str isEqualToString:@"login"]) {
                                                my_AppDelegate.login = YES;

                                            }
                                        }
//                                        my_AppDelegate.assignO = NO;
//                                        my_AppDelegate.auditR = NO;
//                                        my_AppDelegate.grabO = NO;
                                        [self quitLoginViewController];
                                    });
                                }
                            } failure:^(NSError *error) {
                                [SVProgressHUD showErrorWithStatus:@"登录失败"];
                            }];
                        });
                    }else{
                        NSString *msg = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msg"]];
                        [SVProgressHUD showErrorWithStatus:msg];
                        [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [SVProgressHUD dismiss];
                        });
                    }
                } failure:^(NSError *error) {
                    [SVProgressHUD showErrorWithStatus:@"登录超时"];
                }];
            }else {
                [SVProgressHUD showErrorWithStatus:@"请输入正确的账号密码"];
                [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
            }
        }
}


#pragma mark - 懒加载

- (IBAction)changPasswordClick:(id)sender {
    changepasswordController * vc = [changepasswordController new];
    [self presentViewController:vc animated:YES completion:nil];
}

- (NetWorking *)request {
    
    if (!_request) {
        _request = [[NetWorking alloc] init];
        _request.delegate = self;
    }
    return _request;
}


//登录
- (void)quitLoginViewController
{
    [my_AppDelegate.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
    ZXTabBarController *tabController = [[ZXTabBarController alloc] init];
    my_AppDelegate.window.rootViewController = tabController;
}
-(void)session{
    // 快捷方式获得session对象
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"http://www.daka.com/login?username=daka&pwd=123"];
    // 通过URL初始化task,在block内部可以直接对返回的数据进行处理
    NSURLSessionTask *task = [session dataTaskWithURL:url
                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError * error) {
                                        NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
                                    }];
    // 启动任务
    [task resume];
    
}
-(void)session2{
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@user/login",ZTbaseRequestURL]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.timeoutInterval = 10;
    request.HTTPBody = [@"uname=admin&password=123456" dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession *session = [NSURLSession sharedSession];
    // 由于要先对request先行处理,我们通过request初始化task
    NSURLSessionTask *task = [session dataTaskWithRequest:request
                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                            if (data) {
                                                NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
                                            }
                                            
                                        }];
    [task resume];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)huoquyanzhengmaClick:(id)sender {
    NSString * PhoneStr = _phoneNumberTF.text;
    if (PhoneStr.length != 11) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        [SVProgressHUD setBackgroundColor:RGB(85, 85, 85)];
                        [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    [NetWorking startPOSTRequestWithUrl:[NSString stringWithFormat:@"usersendSms"] parameters:@{@"phone":PhoneStr} logMes:@"获取验证码" show:NO success:^(NSDictionary *data) {
        [self openCountdown];
        
    } failure:^(NSError *error) {
        
    }];
}
// 开启倒计时效果
-(void)openCountdown{
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self.huoquyanzhengmaBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.huoquyanzhengmaBtn setTitleColor:RGB(60, 129, 240) forState:UIControlStateNormal];
                self.huoquyanzhengmaBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self.huoquyanzhengmaBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                [self.huoquyanzhengmaBtn setTitleColor:RGB(136, 136, 136) forState:UIControlStateNormal];
                self.huoquyanzhengmaBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}


@end
